module.exports = {
  description: '新建页面',
  prompts: [
    {
      type: 'input',
      name: 'name',
      message: '页面名称',
      validate (value) {
        return !value.trim() ? '请输入页面名称' : true
      }
    },
    {
      type: 'input',
      name: 'url',
      message: '路径(views目录下)'
    },
    {
      type: 'input',
      name: 'filename',
      message: '文件名',
      default: 'index'
    },
    {
      type: 'checkbox',
      name: 'blocks',
      message: '请选择模块',
      choices: [
        {
          name: '<template>',
          value: 'template',
          checked: true
        },
        {
          name: '<script>',
          value: 'script',
          checked: true
        },
        {
          name: '<style>',
          value: 'style',
          checked: true
        }
      ],
      validate (value) {
        return value.indexOf('script') === -1 && value.indexOf('template') === -1 ? '至少拥有script或template模块' : true
      }
    },
    {
      type: 'confirm',
      name: 'wantRouter',
      message: '是否创建路由?',
      default: true
    }
  ],
  actions: data => {
    const actions = [
      {
        type: 'add',
        path: `src/views{{url}}${data.filename === 'index' ? '/{{name}}' : ''}/{{filename}}.vue`,
        templateFile: 'plop-templates/view/index.hbs',
        data: {
          name: '{{name}}',
          template: data.blocks.includes('template'),
          script: data.blocks.includes('script'),
          style: data.blocks.includes('style')
        }
      }
    ]
    let level = 1; let reg = '// append new router'; let superior = ''
    if (data.url) {
      const temp = data.url.split('/')
      level = temp.length >= 3 ? 3 : 2
      superior = temp[level === 2 ? 0 : 1]
      reg = `// append new ${superior}`
    }
    if (data.wantRouter) {
      actions.push({
        type: 'modify',
        path: 'src/router/index.js',
        pattern: new RegExp(reg),
        templateFile: 'plop-templates/view/router.hbs',
        data: {
          name: '{{name}}',
          path: `${data.url}${data.filename === 'index' ? `/${data.name}` : ''}/${data.filename}`,
          superior: superior,
          isChild: level < 3,
          isFirst: level === 1
        }
      })
    }
    return actions
  }
}
